//
//  HappChatServer.swift
//  HappyChat
//
//  Created by guduzhonglao on 10/4/19.
//  Copyright © 2019 onlysea. All rights reserved.
//

import Foundation
import Moya

enum Net {
    case get(url:String,parameters:[String:Any]?)
    case post(url:String,parameters:[String:Any]?)
}

extension Net:TargetType {
    var baseURL: URL {
        switch self {
        case .get(let url, _):
            return URL(string: url)!
        case .post(let url, _):
            return URL(string: url)!
        }
    }
    
    var path: String {
        return ""
    }
    
    var method: Moya.Method {
        switch self {
        case .get(_, _):
            return .get
        case .post(_, _):
            return .post
        }
    }
    
    var sampleData: Data {
        switch self {
        case .get(let url,  let parameters):
            return "plain".utf8Encoded
        case .post(url: _, parameters: _):
            return "post".utf8Encoded
        }
    }
    
    var task: Task {
        switch self {
        case .get(url: _, let parameters):
            if let p = parameters {
                return .requestParameters(parameters: p, encoding: URLEncoding.queryString)
            }else{
                return .requestPlain
            }
        case .post(url: _, let parameters):
            if let p = parameters {
                return .requestParameters(parameters: p, encoding: URLEncoding.queryString)
            }else{
                return .requestPlain
            }
        }
    }
    
    var headers: [String : String]? {
//        let model = UserModel.sharedInstance(UserKey0)
        return ["deviceUUID": UUID.getByKeyChain(),"XX-Token":"","XX-Device-Type":"iphone"]
    }
    
    
}

let HCProvider = MoyaProvider<Net>(plugins: [NetworkLoggerPlugin()])

extension String {
    var urlEscaped: String {
        return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
    }
    
    var utf8Encoded: Data {
        return self.data(using: .utf8)!
    }
}
private func JSONResponseDataFormatter(_ data: Data) -> Data {
    do {
        let dataAsJSON = try JSONSerialization.jsonObject(with: data)
        let prettyData = try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted)
        return prettyData
    } catch {
        return data //fallback to original data if it cant be serialized
    }
}
private func JsonLuBanReq(_ data: Data)-> String{
    do{
        let dataAsJSON = try JSONSerialization.jsonObject(with: data)
        let stringJson = try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted)
        let str =  NSString(data:stringJson ,encoding: String.Encoding.utf8.rawValue)
        return str! as String;
        
        
    }catch {
        let str =  NSString(data:data ,encoding: String.Encoding.utf8.rawValue)
        return  str! as String //fallback to original data if it cant be serialized
    }
}

let reqquestQueue = OperationQueue()

@objc class NetRequest:NSObject {
    private override init() {
        reqquestQueue.maxConcurrentOperationCount = 20;
        reqquestQueue.name = "cn.bj.happtchat"
    }
    static let shared = NetRequest()
    @objc static func get(url:String,parameters:[String:Any]?,seccese:((Any)->Void)?,faild:((Any)->Void)?) {
        NetRequest.shared
        reqquestQueue.addOperation {
            HCProvider.request(.get(url: url, parameters: parameters)) { (result) in
                switch result {
                case .success(let res):
                    do {
                        seccese?(try res.mapJSON())
                    }catch(let err){
                        faild?(err)
                    }
                case .failure(let err):
                    faild?(err.errorUserInfo)
                }
            }
        }
    }
    
    @objc static func post(url:String,parameters:[String:Any]?,seccese:((Any)->Void)?,faild:((Any)->Void)?) {
        NetRequest.shared
        reqquestQueue.addOperation {
            HCProvider.request(.post(url: url, parameters: parameters)) { (result) in
                switch result {
                case .success(let res):
                    do {
                        seccese?(try res.mapJSON())
                    }catch(let err){
                        faild?(err)
                    }
                case .failure(let err):
                    faild?(err.errorUserInfo)
                }
            }
        }
    }
}
